<?php
namespace app\beautiful\controller\admin\mall\pintuan;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\mall\PinTuanGoodsSkuModel;

class Goods extends BaseController{
    protected $name='拼团商品';

    public function index()
    {
        $name=$this->request->param('name');
        $bg_take_count=$this->request->param('bg_take_count/d');
        $end_take_count=$this->request->param('end_take_count/d');
        $status=$this->request->param('status/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        $goods_where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        if(!empty($name)) $goods_where[]=['name','=',$name];
        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];
        $where[]=['goods_id','in',$goods_ids];

        if(!empty($bg_take_count)){
            if(!empty($end_take_count)){
                $where[]=['take_count','between',[$bg_take_count,$end_take_count]];
            }else{
                $where[]=['take_count','>=',$bg_take_count];
            }
        }else{
            if(!empty($end_take_count)){
                $where[]=['take_count','<=',$end_take_count];
            }
        }

        if(!empty($status)) $where[]=['status','=',$status];

        $flash_sale_goods_model= new PinTuanGoodsModel();
        $flash_sale_goods_model = $flash_sale_goods_model->with(['goods']);
        $order=['update_time'=>'desc','pin_tuan_goods_id'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        $return = DataLogic::getDataList($flash_sale_goods_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function show()
    {
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);
        if($pin_tuan_goods_id==0) return $this->success([]);

        if(null === $pin_tuan_goods= PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        $sku=PinTuanGoodsSkuModel::where([['pin_tuan_goods_id','=',$pin_tuan_goods_id],['is_delete','=',0]])->select()->toArray() ?? [];
        $pin_tuan_goods->append(['pin_tuan_time']);
        $detail=[
            'goods'=>$pin_tuan_goods->goods,
            'pin_tuan_price'=>$pin_tuan_goods->pin_tuan_price,
            'group_num'=>$pin_tuan_goods->group_num,
            'pin_tuan_time'=>$pin_tuan_goods->pin_tuan_time,
            'quota'=>$pin_tuan_goods->quota,
            'fictitious_take_count'=>$pin_tuan_goods->fictitious_take_count,
            'is_tui'=>$pin_tuan_goods->is_tui,
            'is_have_sku'=>$pin_tuan_goods->is_have_sku,
            'sku'=>$sku,
            'pin_tuan_info'=>$pin_tuan_goods->pin_tuan_info,
        ];
        return $this->success(['detail'=>$detail]);
    }

    public function save()
    {
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);
        $goods_id = $this->request->param('goods_id/d',0);
        $group_num = $this->request->param('group_num/d',0);
        $pin_tuan_price = $this->request->param('pin_tuan_price/f',0);
        $pin_tuan_time=$this->request->param('pin_tuan_time/a',[]);
        $quota=$this->request->param('quota/d',0);
        $fictitious_take_count=$this->request->param('fictitious_take_count/d',0);
        $is_tui=$this->request->param('is_tui/d',0);
        $is_have_sku=$this->request->param('is_have_sku/d',0);
        $sku=$this->request->param('sku','','security_json_or_array');
        $pin_tuan_info=$this->request->param('pin_tuan_info');

        //判断传来的参数
        if(null === $goods= GoodsModel::find($goods_id)) return $this->error('商品不存在');
        if($goods->is_delete!=0) return $this->error('商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('商品不存在');
        if(empty($group_num) || $group_num <=1) return $this->error('请输入成团人数，且不能小于1');
        if(empty($pin_tuan_price) || $pin_tuan_price<=0) return $this->error('请输入拼团价，且不能小于0');
        if($pin_tuan_price > $goods->original_price) return $this->error('拼团价不能大于商品原价');
        if(empty($pin_tuan_time) ||count($pin_tuan_time) != 2) return $this->error('请选择拼团时间');
        $start_time=$pin_tuan_time[0]; $end_time=$pin_tuan_time[1];
        if(false === $start_time_unix = strtotime($start_time)) return $this->error('请选择正确的拼团开始时间');
        if(false === $end_time_unix = strtotime($end_time)) return $this->error('请选择正确的拼团结束时间');
        if($start_time<date("Y-m-d",$this->request->time())) return $this->error('拼团开始时间不能小于当前时间');
        if($end_time_unix<$start_time_unix) return $this->error('拼团开始时间不能大于结束时间');
        if((empty($quota) || $quota<=0) && $is_have_sku==0) return $this->error('请输入配额，且不能小于0');
        if(empty($fictitious_take_count) || $fictitious_take_count <=0) return $this->error('请输入需要展示的销量');
        if(!in_array($is_tui,[0,1])) return $this->error('未设置是否推荐');
        if(!in_array($is_have_sku,[0,1])) return $this->error('未设置是否有规格');
        if($is_have_sku==1){
            $quota=0;
            if(empty($sku) || !is_array($sku)) return $this->error('请填写规格');
            foreach ($sku as $k => $v){
                if(empty($v['name'])) return $this->error('请输入规格第'.($k+1).'行的名称');
                if(empty($v['original_price']) || $v['original_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的原价，且不能小于0');
                if(empty($v['pin_tuan_price']) || $v['pin_tuan_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的拼团价，且不能小于0');
                if($v['pin_tuan_price'] > $v['original_price']) return $this->error('规格第'.($k+1).'行的拼团价不能大于原价');
                if(empty($v['quota']) || $v['quota'] <= 0) return $this->error('请输入规格第'.($k+1).'行的配额，且不能小于0');
                $quota=$quota+$v['quota'];
            }
        }
        if(empty($pin_tuan_info)) return $this->error('请输入拼团说明');

        //操作
        if($pin_tuan_goods_id != 0){
            if(null === $pin_tuan_goods= PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error($this->name.'不存在');
            if($pin_tuan_goods->is_delete!=0) return $this->error($this->name.'不存在');
            if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            if($pin_tuan_goods->goods_id != $goods_id){
                if(null !== PinTuanGoodsModel::where([
                        ['shop_id','=',$this->request->shopId],
                        ['goods_id','=',$goods_id],
                        ['status','=',1],
                        ['is_delete','=',0],
                        ['end_time','>=',date("Y-m-d",$this->request->time())]
                    ])->find()){
                    return $this->error('这个商品已经参与拼团中');
                }
            }
        }else{
            $pin_tuan_goods = new PinTuanGoodsModel();
            $pin_tuan_goods->shop_id = $this->request->shopId;
            if(null !== PinTuanGoodsModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['goods_id','=',$goods_id],
                    ['status','=',1],
                    ['is_delete','=',0],
                    ['end_time','>=',date("Y-m-d",$this->request->time())]
                ])->find()){
                return $this->error('这个商品已经参与拼团中');
            }
        }
        $pin_tuan_goods->goods_id =$goods_id;
        $pin_tuan_goods->group_num =$group_num;
        $pin_tuan_goods->pin_tuan_price =$pin_tuan_price;
        $pin_tuan_goods->start_time =$start_time;
        $pin_tuan_goods->end_time =$end_time;
        $pin_tuan_goods->quota =$quota;
        $pin_tuan_goods->fictitious_take_count =$fictitious_take_count;
        $pin_tuan_goods->is_tui =$is_tui;
        $pin_tuan_goods->is_have_sku =$is_have_sku;
        $pin_tuan_goods->pin_tuan_info =$pin_tuan_info;
        $pin_tuan_goods->status=1;
        $pin_tuan_goods->update_time=$this->request->time();
        $pin_tuan_goods->save();

        //规格操作
        if($is_have_sku==1){
            $old_pin_tuan_goods_sku=PinTuanGoodsSkuModel::where([
                ['shop_id','=',$this->request->shopId],
                ['pin_tuan_goods_id','=',$pin_tuan_goods->pin_tuan_goods_id],
                ['is_delete','=',0]
            ])->select()->toArray();
            $update_pin_tuan_goods_ids=array_column($sku,'pin_tuan_goods_id') ?? []; $delete_pin_tuan_goods_sku=[];
            $old_pin_tuan_goods_sku_ids=array_column($old_pin_tuan_goods_sku,'pin_tuan_goods_id') ?? [];
            foreach ($old_pin_tuan_goods_sku as $k => $v){
                if(!in_array($v['pin_tuan_goods_id'],$update_pin_tuan_goods_ids)){
                    $v['is_delete']=1;
                    $delete_pin_tuan_goods_sku[]=$v;
                }
            }

            $sku_ids=GoodsSkuModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['goods_id','=',$goods_id],
                    ['is_delete','=',0]
                ])->column('sku_id') ?? [];
            foreach ($sku as $k => $v){
                $sku[$k]['shop_id']=$this->request->shopId;
                $sku[$k]['pin_tuan_goods_id']=$pin_tuan_goods->pin_tuan_goods_id;
                if(isset($v['pin_tuan_goods_sku_id'])){
                    if(!in_array($v['pin_tuan_goods_sku_id'],$old_pin_tuan_goods_sku_ids)) unset($sku[$k]);
                }
                if(isset($v['sku_id'])){
                    if(!in_array($v['sku_id'],$sku_ids)) unset($sku[$k]);
                }
            }
            $new_sku=array_merge($sku,$delete_pin_tuan_goods_sku);
            //更新
            $pin_tuan_goods_sku_model= new PinTuanGoodsSkuModel();
            $pin_tuan_goods_sku_model->saveAll($new_sku);
        }
        return $this->success('保存成功');
    }

    public function undercarriage()
    {
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        if(null === $pin_tuan_goods= PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->status == -1) return $this->error($this->name.'已下架');
        //其他判断后面补充

        $pin_tuan_goods->status=-1;
        $pin_tuan_goods->save();
        return $this->success('下架成功');
    }

    public function grounding()
    {
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        if(null === $pin_tuan_goods= PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($pin_tuan_goods->status == 1) return $this->error($this->name.'已上架');
        //其他判断后面补充

        $pin_tuan_goods->status=1;
        $pin_tuan_goods->update_time=$this->request->time();
        $pin_tuan_goods->save();
        return $this->success('上架成功');
    }
}
